<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\Install\Logic;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\Install\Command\UpgradeCommand;
use MoChat\App\WorkContact\Contract\ContactFieldContract;
use Psr\Container\ContainerInterface;

/**
 * 版本升级逻辑 1.3.1.
 */
class Upgrade1D3D1Logic
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @var ContactFieldContract
     */
    private $contactFieldService;

    /**
     * @var UpgradeCommand
     */
    private $command;

    /**
     * @var CorpContract
     */
    private $corpService;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function __invoke(UpgradeCommand $command)
    {
        $this->command = $command;
        try {
            $this->logger = $this->container->get(StdoutLoggerInterface::class);
            $this->contactFieldService = $this->container->get(ContactFieldContract::class);
            $this->corpService = $this->container->get(CorpContract::class);

            $corps = $this->corpService->getCorps(['id']);
            if (empty($corps)) {
                return;
            }

            $initContactFields = $this->contactFieldService->getInitContactFields();
            if (empty($initContactFields)) {
                return;
            }

            foreach ($corps as $corp) {
                $createData = [];
                foreach ($initContactFields as $field) {
                    $createData[] = [
                        'name' => $field['name'],
                        'label' => $field['label'],
                        'type' => $field['type'],
                        'options' => Json::encode($field['options']),
                        'order' => $field['order'],
                        'status' => $field['status'],
                        'is_sys' => $field['isSys'],
                        'field_type' => $field['fieldType'],
                        'corp_id' => $corp['id'],
                    ];
                }

                if (empty($createData)) {
                    return;
                }

                $this->contactFieldService->createContactFields($createData);
            }
        } catch (\Throwable $e) {
            $this->logger->error(sprintf('初始化企业客户自定义字段失败，错误信息：%s', $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
        }
    }
}
